package etf.jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BlobJDBC {
	private Connection connection;

	public BlobJDBC() {
		connection = JDBCUtil.getConnection();
	}

	public long insertBLOB(String name) {
		long elapsedTime = 0;
		FileInputStream fis = null;
		PreparedStatement ps = null;
		String insertImage = "insert into library_logo(title, image) values (?, ?)";
		try {
			long startTime = System.currentTimeMillis();
			connection.setAutoCommit(false);
			String location = "images/" + name + ".jpg";
			File file = new File(location);
			fis = new FileInputStream(file);
			ps = connection.prepareStatement(insertImage);

			ps.setString(1, name + ".jpg");
			ps.setBinaryStream(2, fis, (int) file.length());
			ps.execute();

			connection.commit();
			long stopTime = System.currentTimeMillis();
			elapsedTime = stopTime - startTime;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return elapsedTime;
	}

	public long readBLOB(String name) {
		long elapsedTime = 0;
		String sql = "SELECT title,image FROM library_logo where title = ?";
		PreparedStatement stmt = null;
		ResultSet resultSet = null;
		FileOutputStream fos = null;
		try {

			long startTime = System.currentTimeMillis();
			connection.setAutoCommit(false);
			stmt = connection.prepareStatement(sql);
			stmt.setString(1, name + ".jpg");
			resultSet = stmt.executeQuery();
			while (resultSet.next()) {
				String title = resultSet.getString(1);
				File image = new File("D:\\xjdbc\\" + title);
				fos = new FileOutputStream(image);

				byte[] buffer = new byte[1];
				InputStream is = resultSet.getBinaryStream(2);
				while (is.read(buffer) > 0) {
					fos.write(buffer);
				}
				fos.close();
			}

			connection.commit();
			long stopTime = System.currentTimeMillis();
			elapsedTime = stopTime - startTime;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return elapsedTime;
	}

	public void closeSession() {
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

}
